﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.PresentationFramework.ApplicationModel;
using Caliburn.Core.Metadata;
using Luna.WPF.ApplicationFramework;
using XWord.Fundamental.Domain.Model;
using Microsoft.Practices.ServiceLocation;
using XWord.Fundamental.Domain;
using System.Threading;
using XWord.WPF.ApplicationFramework;
using Caliburn.PresentationFramework.Actions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;
using System.Windows;
using XWord.WPF.ApplicationFramework.Threads;
using XWord.GUI.Presenters.Interface;
using XWord.Fundamental.Domain.Services;
namespace XWord.GUI.Presenters.Fundamental
{
  
    [Singleton("WordExplorer", typeof(IWordExplorerPresenter))]
    public class WordExplorerPresenter : DockingPresenter, IWordExplorerPresenter
    {
        
        private IServiceLocator _serviceLocator;
        public WordExplorerPresenter(IServiceLocator entityFactory)
        {
            _serviceLocator = entityFactory;
            this.DisplayName = "单词";
            this.IsOpen = true;
            ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) => {

                IWordService wordSv = RemotingServiceFactory.GetWordService();
                AllWordList = wordSv.GetAllWord().ToList();
                //AllWordList = BinaryFormatterHelper.Deserialize<IList<string>>(BinaryFormatterHelper.Path + "AllWordList2.data");
                //var list = new List<string>();
                //foreach (var item in AllWordList)
                //{
                //    list.Add(item.Name);
                //}
                //BinaryFormatterHelper.Serialize(BinaryFormatterHelper.Path + "AllWordList2.data", list);
                //var dict = new Dict();
                //List<string> lst = new List<string>();
                //foreach (var item in AllWordList)
                //{
                //    string w = new string();
                //    w.Name = item.Name;
                //    //w.Comment = item.Comment;
                //    //w.Pron = item.Pron;
                //    lst.Add(w);
                //    //dict.SetCurrentKey(item.Name);
                //    //dict.Add("Comment", item.Comment);
                //    //dict.Add("Pron", item.Pron);
                //}
                //BinaryFormatterHelper.Serialize("AllWordList3.data", lst);
                // AllWordList = list;
                //foreach (var item in list)
                //{
                //    var word = new Word() { Name = item.ToString() };
                //    AllWordList.Add(word);
                //}
               
            }));
         //   WordList = _wordModel.LoadWordList();
        }


        public IList<string> AllWordList { get; set; }

        private IList<string> _wordList;
        public IList<string> WordList
        {
            get { return _wordList ?? (_wordList = new List<string>()); }
            set
            {
                _wordList = value;
                NotifyOfPropertyChange("WordList");
            }
        }
        [AsyncAction]
        public void SearchWord(string Name)
        {
            Name = Name.ToLower().Trim();
            if (AllWordList == null) return;
            WordList = AllWordList.Where(e => CheckWordLength(e.ToLower(), Name.ToLower()) && SearchFilerWord(e.ToLower(), Name.ToLower())).ToObservableCollection();
        }

        private bool CheckWordLength(string word, string searchName)
        {
            int count = 0;
            var countStr = searchName.Split(new char[] { ':' });
            if (countStr.Length > 1 && !string.IsNullOrEmpty(countStr[1]))
                count = int.Parse(countStr[1]);
            if (count > 0)
                return word.Length == count;
            return true;
        }

        private bool SearchFilerWord(string word, string searchName)
        {
            if (searchName.Contains(":"))
            {
                searchName = searchName.Substring(0, searchName.IndexOf(":"));
            }
            var length = searchName.Length;
            var array = searchName.Split(new char[] { '*' });

            if (array.Length == 1)
                return word.StartsWith(searchName);
            if (array.Length == 2)
            {
                if (string.IsNullOrEmpty(array[0]))
                    return word.EndsWith(array[1]);
                else
                    return word.StartsWith(array[0]) && word.EndsWith(array[1]);
            }

            if (array.Length >= 3)
            {
                var list = new List<bool>();
                for (int i = 0; i < (array.Length - 2); i++)
                {
                    list.Add(word.Substring(searchName.IndexOf("*")).Contains(array[i + 1]));
                }
                return ChcekStartEnd(word, array[0], true) && !list.Contains(false) && ChcekStartEnd(word, array[array.Length - 1], false);
            }
            //a*ion,*ion
            return true;
        }

        private bool ChcekStartEnd(string word, string searchName, bool IsStart)
        {
            if (string.IsNullOrEmpty(searchName)) return true;
            if (IsStart)
                return word.StartsWith(searchName);
            else
                return word.EndsWith(searchName);
        }



        public void SearchEtymaWord(string EtymaorWord)
        {
            if (string.IsNullOrEmpty(EtymaorWord)) return;

            IList<EtymaMessage> messageList = EtymaLibraryExplorerPresenter.ParseText(EtymaorWord);
            if (messageList.Any(e => e.EtymaType == EtymaType.Etymon))
            {
                WordList = AllWordList.Where(e => messageList.Any(msg => e.Contains(msg.Name))).Select(e => e).ToArray();
            }
            else
            {
                WordList = AllWordList.Where(e => messageList.Any
                    (msg => (e.StartsWith(msg.Name) && msg.EtymaType == EtymaType.PreFix)
                    || (e.EndsWith(msg.Name) && msg.EtymaType == EtymaType.Suffix))).Select(e => e)
                    .ToArray();
            }
        }

        private string _searchWord=string.Empty;
        public string SelectedWord
        {
            get { return _searchWord; }
            set
            {
                _searchWord = value;
                NotifyOfPropertyChange("SelectedWord");
            }
        }

        private bool _isOpen;
        public bool IsOpen
        {
            get { return _isOpen; }
            set
            {
                _isOpen = value;
                NotifyOfPropertyChange("IsOpen");
            }
        }

        private string _wordTip;
        public string WordTip
        {
            get { return _wordTip; }
            set
            {
                _wordTip = value;
                NotifyOfPropertyChange("WordTip");
            }
        }

        public void AddWord(IDataObject obj)
        {
            //WordTip = "正在添加单词";
            //IsOpen = true;
            
            //var str = Convert.ToString(obj.GetData(DataFormats.UnicodeText));
            //if (string.IsNullOrEmpty(str))
            //{
            //    IsOpen = false;
            //    return;
            //}
            //WordImport import = new WordImport();
            //import.ImportWord(str,
            //    (Word word) => { return !AllWordList.Any(ee => ee.Name.Trim() == word.Name); },
            //    ((Word word) =>
            //    {
            //        word.CreateTime = DateTime.Now;
            //        AllWordList.Add(word);
            //        WordList.Insert(0,word);
            //        WordTip = string.Format("{0}添加成功", str);
            //        GapDispatcherTimer.BeginInvoke(1, () =>
            //        {
            //            IsOpen = false;
            //        });
            //    }),
            //    ((Word word) =>
            //    {
            //        WordTip = string.Format("{0}已经在列表中", str);
            //        GapDispatcherTimer.BeginInvoke(1, () =>
            //        {
            //            IsOpen = false;
            //        });
            //    }));
        }


        public string SelectedItem
        {
            get
            {
                if (SelectedWord != null)
                    return SelectedWord;
                return string.Empty;
            }
            set {
                SelectedWord=value;
            }
        }
    }

    //[Serializable]
    //public class string
    //{
    //    public string Name { get; set; }
    //}
}
